import { localCache } from '@/utils/cache'
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { addRoute } from './dynamics-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },

  {
    path: '/main',
    name: 'Main',
    component: () => import('@/views/main/main.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404/index.vue')
  }
]

const router = createRouter({
  // 路径中存在#
  history: createWebHashHistory(),
  routes
})

let reload = false

router.beforeEach((to) => {
  const token = localCache.get('token')

  if (token) {
    if (!reload) {
      addRoute()
      reload = true
      return to.fullPath
    }
    if (to.path === '/login') {

      return '/main'
    }
    if (to.path === '/main') {

      return '/main/home'
    }
  } else if (to.path !== '/login') {
    return '/login'
  }
})

export default router
